/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.prepare;

import cn.ac.nercis.pes.common.constant.common.BaseConstants;
import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.common.utils.RichTextUtil;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.photo.ThumbnailControl;
import cn.ac.nercis.pes.community.constant.SaveMethod;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.prepare.PrepareView;
import cn.ac.nercis.pes.model.dto.evaluation.content.BusinessConditionDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationContentService;
import cn.ac.nercis.pes.service.utils.FileManage;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 承载的业务情况管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class BusinessController implements Initializable, GlobalEventHandle, InitEvalDataLoad {

    @FXML
    private StackPane page;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;
    @FXML
    private TextArea businessConditionEditor;
    @FXML
    private VBox pictureBox;
    @FXML
    private Button addPictureBtn;

    private final EvaluationContentService evaluationContentService;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);
    private String currentSystemId;

    public BusinessController() {
        this.evaluationContentService = SpringUtils.getBean(EvaluationContentService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        addPictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerTextChange(this.businessConditionEditor);
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化承载的业务情况信息...");
        this.currentSystemId = systemId;
        this.loadBusinessCondition();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        save(SaveMethod.SAVE, false);
    }

    @FXML
    public void onTmpSave() {
        LogUtils.info(log, "执行暂存操作...");
        save(SaveMethod.SAVE, false);
    }

    @FXML
    public void onFinishSave() {
        LogUtils.info(log, "执行保存操作...");
        save(SaveMethod.SAVE, true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        save(SaveMethod.SAVE_NOW, false);
    }

    @FXML
    private void onAddPictureClick() {
        LogUtils.info(log, "执行添加图片操作...");
        addPicture();
    }

    private void addPicture() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择承载的业务情况图");
        fileChooser.getExtensionFilters().addAll(ControlUtils.getImageExtensionFilters());
        var currentSystem = AppStore.getCurrentSystem(this.currentSystemId);
        File selectFile = fileChooser.showOpenDialog(Objects.requireNonNull(currentSystem).getEvaluationStage());
        if (Objects.isNull(selectFile)) {
            return;
        }
        try {
            File pictureFile = storePictureFile(selectFile);
            loadThumbnailPicture(pictureFile.getName());
            save(SaveMethod.SAVE_NOW, false);
        } catch (IOException ex) {
            log.error("添加承载的业务情况图出错：", ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN)
                    .withMessage("添加承载的业务情况图失败！")
                    .build().show();
        }
    }

    private void loadThumbnailPicture(String pictureName) {
        File pictureFile = FileUtils.getFile(FileManage.getBusinessContentDir(this.currentSystemId), pictureName);
        if (!pictureFile.exists()) {
            return;
        }
        try {
            ThumbnailControl thumbnailControl = new ThumbnailControl(pictureFile,this.page);
            thumbnailControl.setOnRenameEvent(this::onRenameFileChick);
            thumbnailControl.setOnDeleteEvent(this::onDeleteThumbnailClick);
            pictureBox.getChildren().add(thumbnailControl);
        } catch (IOException ex) {
            log.error("加载承载的业务情况图失败：", ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("载入承载的业务情况图失败")
                    .build().show();
        }
    }

    protected void onRenameFileChick(ThumbnailControl source, String oldValue, String newValue) {
        LogUtils.info(log, "执行图片重命名操作...");
        if (StringUtils.isBlank(newValue)) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("承载的业务情况图名不能为空！")
                    .build().show();
            return;
        }
        if (StringUtils.equals(oldValue, newValue)) {
            source.setEditMode(false);
            return;
        }
        String newFileName = newValue.concat(FileManage.getFileSuffix(source.getPictureFile().getName()));
        List<String> fileNames = FileManage.findBusinessFiles(this.currentSystemId)
                .stream()
                .map(File::getName)
                .collect(Collectors.toList());
        if (FileManage.existFileName(newFileName, fileNames)) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL)
                    .withMessage(String.format("当前系统已存在同名的%s文件！", newFileName))
                    .build().show();
        } else {
            boolean result = source.renamePhotoFile(newFileName);
            if (!result) {
                source.renamePhotoFile(oldValue);
                MessageDialog.builder()
                        .withContainer(this.page)
                        .withType(MessageType.FAIL)
                        .withMessage("承载的业务情况图重命名失败！")
                        .build().show();
                return;
            }
            updateRefPhoto(oldValue, newValue);
            source.setEditMode(false);
            save(SaveMethod.SAVE_NOW, false);
        }
    }

    private void updateRefPhoto(String oldName, String newName) {
        this.businessConditionEditor.setText(RichTextUtil.updateRefPhoto(this.businessConditionEditor.getText(), oldName, newName));
    }

    private void onDeleteThumbnailClick(ThumbnailControl source) {
        LogUtils.info(log, "执行图片删除操作...");
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("是否删除当前承载的业务情况图？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm) -> {
            if (!confirm) {
                return;
            }
            this.pictureBox.getChildren().remove(source);
            removeStoreFile(source.getPictureFile());
            save(SaveMethod.SAVE_NOW, false);
        });
    }

    private String collectPhotoFiles() {
        return this.pictureBox.getChildren()
                .stream()
                .filter(n -> n instanceof ThumbnailControl)
                .map(n -> (ThumbnailControl) n)
                .map(ThumbnailControl::getPictureFile)
                .map(File::getName)
                .collect(Collectors.joining(BaseConstants.MULTI_SPLIT_CHAR));

    }

    private File storePictureFile(@NonNull File file) throws IOException {
        String fileDir = FileManage.getBusinessContentDir(this.currentSystemId);
        List<String> fileNames = FileManage.findBusinessFiles(this.currentSystemId)
                .stream()
                .map(File::getName)
                .collect(Collectors.toList());
        File distFile;
        if (FileManage.existFileName(file.getName(), fileNames)) {
            distFile = FileUtils.getFile(fileDir, FileManage.getFileRename(file.getName(), fileNames));
        } else {
            distFile = FileUtils.getFile(fileDir, file.getName());
        }
        FileManage.copyFile(file, distFile);
        return distFile;
    }

    private void removeStoreFile(@NonNull File file) {
        try {
            FileUtils.delete(file);
        } catch (IOException ex) {
            log.error(String.format("删除%s承载的业务情况图文件失败：", file.getName()), ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("移除承载的业务情况图文件失败")
                    .build().show();
        }
    }

    private void save(SaveMethod saveMethod, boolean finish) {
        if (StringUtils.isBlank(this.businessConditionEditor.getText())) {
            AppUtils.showMessageDialog("承载的业务情况内容不能为空",MessageType.FAIL,this.page);
            return;
        }
        BusinessConditionDTO businessCondition = BusinessConditionDTO.builder()
                .content(StringUtils.trim(this.businessConditionEditor.getText()))
                .contentPicture(this.collectPhotoFiles())
                .build();
        LogUtils.info(log, "保存承载的业务情况信息...");
        LogUtils.record(log, "请求数据：systemId:{},data:{}", this.currentSystemId, businessCondition);
        CompletableFuture.supplyAsync(() -> this.evaluationContentService.saveBusinessCondition(this.currentSystemId, businessCondition))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshFinishProcess(finish);
                        if (saveMethod == SaveMethod.SAVE) {
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                    } else {
                        if(saveMethod == SaveMethod.SAVE_NOW){
                            log.error("即时保存失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存承载的业务情况信息出错!", ex);
                    return null;
                });
    }

    private void refreshFinishProcess(boolean finish) {
        var prepareView = AppStore.getEvaluationView(this.currentSystemId, PrepareView.class);
        if(prepareView.getController() instanceof PrepareController controller){
            controller.setEvalProcess(EvaluationModule.BUSINESS, finish ? FinishState.FINISH:FinishState.INCOMPLETE);
        }
    }

    private void loadBusinessCondition() {
        LogUtils.info(log, "获取承载的业务情况信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.evaluationContentService.findBusinessCondition(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    this.businessConditionEditor.setText(res.getContent());
                    this.initBusinessFiles();
                }))
                .exceptionally((ex) -> {
                    log.error("获取承载的业务情况信息出错!", ex);
                    return null;
                });
    }

    private void initBusinessFiles() {
        //清空页面旧的图片
        pictureBox.getChildren().clear();
        FileManage.findBusinessFiles(this.currentSystemId)
                .stream()
                .map(File::getName)
                .forEach(this::loadThumbnailPicture);
    }


}